<template>
  <div>
    <a-modal
      v-model:visible="visible"
      :title="noticepageinfo.notificationId ? '修改通知信息' : '发布通知信息'"
      @cancel="visible = false"
      @before-ok="handleBeforeOk"
    >
      <a-form :model="noticepageinfo" ref="formRef">
        <a-form-item
          field="title"
          label="通知标题"
          :rules="[{ required: true, message: '报名标题不能为空' }]"
          validate-trigger="blur"
        >
          <a-input
            style="width: 350px"
            v-model="noticepageinfo.title"
            placeholder="请输入通知标题"
          />
        </a-form-item>

        <a-form-item
          field="notificationType"
          label="通知类型"
          :rules="[{ required: true, message: '请选择通知类型' }]"
          validate-trigger="change"
        >
          <a-select
            v-model="noticepageinfo.notificationType"
            style="width: 350px"
            placeholder="请选择通知类型"
          >
            <a-option value="0">学校消息</a-option>
            <a-option value="1">班级消息</a-option>
            <a-option value="2">活动日常</a-option>
          </a-select>
        </a-form-item>

        <a-form-item
          field="content"
          label="通知内容"
          :rules="[{ required: true, message: '通知内容不能为空' }]"
          validate-trigger="blur"
        >
          <a-textarea
            style="width: 350px"
            v-model="noticepageinfo.content"
            placeholder="请输入通知内容"
          />
        </a-form-item>

        <a-form-item
          field="enrollPersonNum"
          label="上传图片"
          validate-trigger="blur"
        >
          <a-upload
            list-type="picture-card"
            action="/"
            :file-list="fileList"
            image-preview
            @before-upload="beforeUpload"
            :on-before-remove="handleRemove"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-card>
      <a-space size="medium">
        <a-input-search
          :style="{ width: '280px' }"
          placeholder="请输入通知标题"
          search-button
          @search="getErollListByTitle"
          v-model="keyword"
        />
        <a-button @click="openVisible" type="primary">
          <template #icon>
            <icon-plus />
          </template>
          <template #default>发布通知</template>
        </a-button>
        <a-popconfirm content="你确定要删除这些通知吗?" @ok="batchDelete">
          <a-button type="primary" status="danger">
            <template #icon>
              <icon-delete />
            </template>
            <template #default>批量删除</template>
          </a-button>
        </a-popconfirm>
      </a-space>
    </a-card>

    <a-card>
      <!-- 这里是表的复选框 -->
      <a-table
        :data="noticeInfoList"
        :bordered="{ cell: true }"
        :pagination="false"
        row-key="notificationId"
        :rowSelection="{
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false,
        }"
        v-model:selectedKeys="selectEroll"
      >
        <template #columns>
          <a-table-column title="通知标题" data-index="title"></a-table-column>
          <a-table-column
            title="通知内容"
            data-index="content"
          ></a-table-column>
          <a-table-column
            title="通知时间"
            data-index="publishDate"
          > <template #cell="{ record }">
              {{ formattedDate(record.publishDate) }}
            </template></a-table-column>
          <a-table-column title="操作">
            <template #cell="{ record }">
              <a-space>
                <a-popconfirm
                  @ok="deleteEroll(record)"
                  content="你确定要删除吗?"
                >
                  <a-button size="mini" status="danger">
                    <template #icon></template>
                    <template #default>删除</template>
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>

      <a-pagination
        @change="getEnrollInfo"
        @page-size-change="pageSizeChange"
        style="margin-top: 15px"
        :total="total"
        show-total
        show-page-size
        :page-size="pageSize"
        :current="pageNo"
      />
    </a-card>
  </div>
</template>
<script setup lang="ts">
import { IconDelete, IconPlus } from '@arco-design/web-vue/es/icon'
import {
  reqNoticeInfoList,
  reqNoticeBytitleInfoPage,
  DeleteNoTifIcationByIds,
  DeleteNoTifIcationById,
  addOrUpdatNotificationInfo,
} from '@/api/notice/index'
import { onMounted, reactive, ref, nextTick } from 'vue'
import { NoticePageInfo } from '@/api/notice/type'
import { Message } from '@arco-design/web-vue'
import { reqUploadImage } from '@/api/publicApi'

let noticeInfoArr = ref([])
let noticeInfoList = ref([])
let total = ref<number>(0)
let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
let keyword = ref<String>()
let selectEroll = ref([])
let formRef = ref()
let dateRange = ref()
const visible = ref(false)
//存放文件列表
const fileList = ref<any>([])

const noticepageinfo: NoticePageInfo = reactive({
  title: '', //标题
  image: '', //图片
  notificationType: '', //通知类型
  content: '', //内容
  publishDate: '',    //发布日期
  publisherId: 9999999, //发布者ID
})

// 页码改变
const pageSizeChange = (value: number) => {
  pageSize.value = value
  getEnrollInfo(pageNo.value)
}

// 获取通知数据
const getEnrollInfo = async (pager = 1) => {
  // 收集当前的页码
  pageNo.value = pager
  let result: any = await reqNoticeInfoList(pageNo.value, pageSize.value)
  console.log('我是通知管理' + result)

  if (result.status === 'OK') {
    noticeInfoList.value = result.data.records
    total.value = result.data.total
  }
}

// 通过标题搜索
const getErollListByTitle = async () => {
  if (keyword.value) {
    let result: any = await reqNoticeBytitleInfoPage(
      pageNo.value,
      pageSize.value,
      keyword.value,
    )
    if (result.status === 'OK') {
      console.log(result)

      noticeInfoList.value = result.data.records
    }
  } else {
    getEnrollInfo()
  }
}
//批量删除
const batchDelete = async () => {
  if (selectEroll.value.length < 1) {
    Notification.warning({
      title: '删除提示',
      content: '请选择你要删除的用户!',
    })
    return
  }
  console.log('你好' + selectEroll.value)
  let result = await DeleteNoTifIcationByIds(selectEroll.value)
  console.log(result.status)

  if (result.status === 'OK') {
    Message.success(result.message)
    getEnrollInfo(pageNo.value)
  }
}

// 删除
const deleteEroll = async (_record: any) => {
  console.log('这是ID：' + _record)
  let result: any = await DeleteNoTifIcationById(_record)

  console.log('88888:' + result.status)

  if (result.status === 'OK') {
    Message.success(result.message)
    getEnrollInfo(
      noticeInfoArr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  }
}

// 打开模态框
const openVisible = () => {
  Object.assign(noticepageinfo, {
    // notificationId: 0, //ID
    title: '', //标题
    image: '', //图片
    // notificationType: , //通知类型
    content: '', //内容
    // publishDate: number[]    //发布日期
    // publisherId: , //发布者ID
  })
  dateRange.value = ['', '']
  fileList.value = []
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate()
  })
  visible.value = true
}

// 模态框点击确定
const handleBeforeOk = () => {
  // enrollParams.enrollStartTime = convertStringToTimeArray(dateRange.value[0])
  // enrollParams.enrollEndTime = convertStringToTimeArray(dateRange.value[1])
  formRef.value.validate(async (r: any, _Record: any) => {
    if (r === undefined) {
      // 发送请求
      console.log(fileList.value)

      let arr = fileList.value.map((item: any) => {
        console.log('内部' + item.url)
        return item.url
      })
      console.log('arr:' + arr)

      noticepageinfo.image = arr.join(',')
      console.log('我是图片：' + noticepageinfo.image)
      let result = await addOrUpdatNotificationInfo(noticepageinfo)
      console.log('成功还是失败？' + result)
      if (result.status === 'OK') {
        Message.success(result.message)
        getEnrollInfo()
        visible.value = false
        fileList.value = []
      } else {
        Message.error(result.message)
      }
    }
  })
}

// 格式化时间戳
const formattedDate = (dateParts: any) => {
  let date = new Date(
    dateParts[0],
    dateParts[1] - 1,
    dateParts[2],
    dateParts[3],
    dateParts[4],
    dateParts[5],
  )
  // 转换为格式化的日期字符串
  let year = date.getFullYear()
  let month = ('0' + (date.getMonth() + 1)).slice(-2)
  let day = ('0' + date.getDate()).slice(-2)
  let hours = ('0' + date.getHours()).slice(-2)
  let minutes = ('0' + date.getMinutes()).slice(-2)
  let seconds = ('0' + date.getSeconds()).slice(-2)

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 文件上传成功的回调
const beforeUpload = async (file: File) => {
  const forms = new FormData()
  console.log(file)
  forms.append('image', file) // 获取上传图片信息
  let result = await reqUploadImage(forms) //上传图片至和后台文件中
  let obj = {
    url: getImageUrl(result), //格式化图片路径
  }
  fileList.value.push(obj) //将图片路径添加到fileList中
}

// 删除图片时触发
const handleRemove = (fileItem: any) => {
  //回调函数检查fileItem的url是否与item的url不同
  fileList.value = fileList.value.filter((item: any) => {
    // 如果fileItem的url与当前item的url不相等
    return fileItem.url !== item.url
  })
}

// 格式化图片路径
const getImageUrl = (imageUrl: any) => {
  if (imageUrl) {
    // 拼接后端服务器地址和图片地址
    return `http://localhost:8081${imageUrl}`
  }
}

const getNoticeInfo = async () => {
  let result = await reqNoticeInfoList(1, 5)
  console.log(result)

  noticeInfoList.value = result.data.records
  total.value = result.data.total
}

onMounted(() => {
  getNoticeInfo()
})
</script>
